package net.sf.xoperator.namespaces;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.openbbs.blackboard.filter.KindOfFilter;
import org.openbbs.blackboard.ks.KSExecutionContext;

import net.sf.xoperator.blackboard.ConfigurationAwareKnowledgeSource;
import net.sf.xoperator.configuration.KSConfiguration;
import net.sf.xoperator.rdfxmpp.SPARQLQuery;

public class NamespaceKS extends ConfigurationAwareKnowledgeSource {

	private Map<String, NamespaceConf> confs = new HashMap<String, NamespaceConf>();

	@Override
	public void executeInternal(KSExecutionContext context) {
		SPARQLQuery query = (SPARQLQuery) context.blackboard().read(
				new KindOfFilter(SPARQLQuery.class));
		//add all the namepsaces to the query
		String prefix = "";
		for (NamespaceConf conf : this.confs.values()) {
			prefix += "PREFIX "+conf.getPrefix()+": <" +conf.getUrl()+ "> \n";
		}
		query.setQuery(prefix + query.getQuery());
		context.blackboard().write(new NamespaceSetFlag(query,this.confs.values()));
		
		

	}

	@Override
	public List<Class<? extends KSConfiguration>> getConfigurationClasses() {
		List<Class<? extends KSConfiguration>> classes = new ArrayList<Class<? extends KSConfiguration>>();
		classes.add(NamespaceConf.class);
		return classes;
	}

	@Override
	public boolean isEnabledInternal(KSExecutionContext context) {
		return context.blackboard().exists(new KindOfFilter(SPARQLQuery.class))&&!context.blackboard().exists(new KindOfFilter(NamespaceSetFlag.class));
	}

	@Override
	public void configure(KSConfiguration config) throws Exception {
		NamespaceConf conf = (NamespaceConf) config;
		if (!conf.isObsolete()) {
			this.confs.put(conf.getPrefix(), conf);
		} else {
			this.confs.remove(conf.getPrefix());
		}

	}

}
